#!/usr/bin/python

"""A tool to report some statistics about a formspring account based
on a sqlite database generated with formspringscrape. To see how to
use this, run it without any arguments.
"""

import collections
import operator
import os
import re
import sqlite3
import sys

NUM_MOST_COMMON_WORDS = 15

# Stop words that are not to be included in word counts. This is a superset
# of the list at: http://www.webconfs.com/stop-words.php
STOP_WORDS = set(['-', 'a', "a's", 'able', 'about', 'above', 'abroad', 'according', 'accordingly', 'across', 'actually', 'adj', 'after', 'afterwards', 'again', 'against', 'ago', 'ahead', "ain't", 'all', 'allow', 'allows', 'almost', 'alone', 'along', 'alongside', 'already', 'also', 'although', 'always', 'am', 'amid', 'amidst', 'among', 'amongst', 'an', 'and', 'another', 'any', 'anybody', 'anyhow', 'anyone', 'anything', 'anyway', 'anyways', 'anywhere', 'apart', 'appear', 'appreciate', 'appropriate', 'are', "aren't", 'around', 'as', 'aside', 'ask', 'asking', 'associated', 'at', 'available', 'away', 'awfully', 'back', 'backward', 'backwards', 'be', 'became', 'because', 'become', 'becomes', 'becoming', 'been', 'before', 'beforehand', 'begin', 'behind', 'being', 'believe', 'below', 'beside', 'besides', 'best', 'better', 'between', 'beyond', 'both', 'brief', 'but', 'by', "c'mon", "c's", 'came', 'can', "can't", 'cannot', 'cant', 'caption', 'cause', 'causes', 'certain', 'certainly', 'changes', 'clearly', 'co', 'co.', 'com', 'come', 'comes', 'concerning', 'consequently', 'consider', 'considering', 'contain', 'containing', 'contains', 'corresponding', 'could', "couldn't", 'course', 'currently', 'dare', "daren't", 'definitely', 'described', 'despite', 'did', "didn't", 'different', 'directly', 'do', 'does', "doesn't", 'doing', "don't", 'done', 'down', 'downwards', 'during', 'each', 'edu', 'eg', 'eight', 'eighty', 'either', 'else', 'elsewhere', 'end', 'ending', 'enough', 'entirely', 'especially', 'et', 'etc', 'even', 'ever', 'evermore', 'every', 'everybody', 'everyone', 'everything', 'everywhere', 'ex', 'exactly', 'example', 'except', 'fairly', 'far', 'farther', 'few', 'fewer', 'fifth', 'first', 'five', 'followed', 'following', 'follows', 'for', 'forever', 'former', 'formerly', 'forth', 'forward', 'found', 'four', 'from', 'further', 'furthermore', 'get', 'gets', 'getting', 'given', 'gives', 'go', 'goes', 'going', 'gone', 'got', 'gotten', 'greetings', 'had', "hadn't", 'half', 'happens', 'hardly', 'has', "hasn't", 'have', "haven't", 'having', 'he', "he'd", "he'll", "he's", 'hello', 'help', 'hence', 'her', 'here', "here's", 'hereafter', 'hereby', 'herein', 'hereupon', 'hers', 'herself', 'hi', 'him', 'himself', 'his', 'hither', 'hopefully', 'how', 'howbeit', 'however', 'hundred', "i'd", "i'll", "i'm", "i've", 'i', 'ie', 'if', 'ignored', 'immediate', 'in', 'inasmuch', 'inc', 'inc.', 'indeed', 'indicate', 'indicated', 'indicates', 'inner', 'inside', 'insofar', 'instead', 'into', 'inward', 'is', "isn't", 'it', "it'd", "it'll", "it's", 'its', 'itself', 'just', 'k', 'keep', 'keeps', 'kept', 'know', 'known', 'knows', 'lot', 'last', 'lately', 'later', 'latter', 'latterly', 'least', 'less', 'lest', 'let', "let's", 'like', 'liked', 'likely', 'likewise', 'little', 'look', 'looking', 'looks', 'low', 'lower', 'ltd', 'made', 'mainly', 'make', 'makes', 'many', 'may', 'maybe', "mayn't", 'me', 'mean', 'meantime', 'meanwhile', 'merely', 'might', "mightn't", 'mine', 'minus', 'miss', 'more', 'moreover', 'most', 'mostly', 'mr', 'mrs', 'much', 'must', "mustn't", 'my', 'myself', 'name', 'namely', 'nd', 'near', 'nearly', 'necessary', 'need', "needn't", 'needs', 'neither', 'never', 'neverf', 'neverless', 'nevertheless', 'new', 'next', 'nine', 'ninety', 'no', 'no-one', 'nobody', 'non', 'none', 'nonetheless', 'noone', 'nor', 'normally', 'not', 'nothing', 'notwithstanding', 'novel', 'now', 'nowhere', 'obviously', 'of', 'off', 'often', 'oh', 'ok', 'okay', 'old', 'on', 'once', 'one', "one's", 'ones', 'only', 'onto', 'opposite', 'or', 'other', 'others', 'otherwise', 'ought', "oughtn't", 'our', 'ours', 'ourselves', 'out', 'outside', 'over', 'overall', 'own', 'particular', 'particularly', 'past', 'per', 'perhaps', 'placed', 'please', 'plus', 'possible', 'presumably', 'probably', 'provided', 'provides', 'que', 'quite', 'qv', 'rather', 'rd', 're', 'really', 'reasonably', 'recent', 'recently', 'regarding', 'regardless', 'regards', 'relatively', 'respectively', 'right', 'round', 'said', 'same', 'saw', 'say', 'saying', 'says', 'second', 'secondly', 'see', 'seeing', 'seem', 'seemed', 'seeming', 'seems', 'seen', 'self', 'selves', 'sensible', 'sent', 'serious', 'seriously', 'seven', 'several', 'shall', "shan't", 'she', "she'd", "she'll", "she's", 'should', "shouldn't", 'since', 'six', 'so', 'some', 'somebody', 'someday', 'somehow', 'someone', 'something', 'sometime', 'sometimes', 'somewhat', 'somewhere', 'soon', 'sorry', 'specified', 'specify', 'specifying', 'still', 'sub', 'such', 'sup', 'sure', "t's", 'take', 'taken', 'taking', 'tell', 'tends', 'th', 'than', 'thank', 'thanks', 'thanx', 'that', "that'll", "that's", "that've", 'thats', 'the', 'their', 'theirs', 'them', 'themselves', 'then', 'thence', 'there', "there'd", "there'll", "there're", "there's", "there've", 'thereafter', 'thereby', 'therefore', 'therein', 'theres', 'thereupon', 'these', 'they', "they'd", "they'll", "they're", "they've", 'thing', 'things', 'think', 'third', 'thirty', 'this', 'thorough', 'thoroughly', 'those', 'though', 'three', 'through', 'throughout', 'thru', 'thus', 'till', 'to', 'together', 'too', 'took', 'toward', 'towards', 'tried', 'tries', 'truly', 'try', 'trying', 'twice', 'two', 'un', 'under', 'underneath', 'undoing', 'unfortunately', 'unless', 'unlike', 'unlikely', 'until', 'unto', 'up', 'upon', 'upwards', 'us', 'use', 'used', 'useful', 'uses', 'using', 'usually', 'v', 'value', 'various', 'versus', 'very', 'via', 'viz', 'vs', 'want', 'wants', 'was', "wasn't", 'way', 'we', "we'd", "we'll", "we're", "we've", 'welcome', 'well', 'went', 'were', "weren't", 'what', "what'll", "what's", "what've", 'whatever', 'when', 'whence', 'whenever', 'where', "where's", 'whereafter', 'whereas', 'whereby', 'wherein', 'whereupon', 'wherever', 'whether', 'which', 'whichever', 'while', 'whilst', 'whither', 'who', "who'd", "who'll", "who's", 'whoever', 'whole', 'whom', 'whomever', 'whose', 'why', 'will', 'willing', 'wish', 'with', 'within', 'without', "won't", 'wonder', 'would', "wouldn't", 'yes', 'yet', 'you', "you'd", "you'll", "you're", "you've", 'your', 'yours', 'yourself', 'yourselves', 'zero'])
        


def main():
    db_fname, = parse_args()

    if not os.path.exists(db_fname):
        print 'The sqlite database', db_fname, 'does not exist.'
        sys.exit(1)

    db_conn = sqlite3.connect(db_fname)
    db = db_conn.cursor()
    
    # I know an online algorithm may be more efficient, but I don't think
    # the time savings are that significant for the intended use case.
    items = []
    Item = collections.namedtuple('Item', 'id question answer time username')

    db.execute('SELECT id, question, answer, time, username FROM questions')

    for item_id, question, answer, time, username in db.fetchall():
        username = username or 'Anonymous'
        item = Item(item_id, question, answer, time, username)
        items.append(item)
    
    # Most common askers
    user_counts = collections.defaultdict(int) # default 0
    for username in [item.username for item in items]:
        user_counts[username] += 1

    most_common_askers = sorted(user_counts.items(),
                                key=operator.itemgetter(1),
                                reverse=True)[:NUM_MOST_COMMON_WORDS]
    
    # Most common question words and answer words
    question_word_counts = get_word_counts((item.question for item in items))
    most_common_question_words = sorted(question_word_counts.items(),
                                        key=operator.itemgetter(1),
                                        reverse=True)[:NUM_MOST_COMMON_WORDS]
    
    answer_word_counts = get_word_counts((item.answer for item in items))
    most_common_answer_words = sorted(answer_word_counts.items(),
                                      key=operator.itemgetter(1),
                                      reverse=True)[:NUM_MOST_COMMON_WORDS]

    # Mean and median length for questions and answers
    mean_question_len = mean([len(item.question) for item in items])
    mean_answer_len = mean([len(item.answer) for item in items])
    
    median_question_len = median([len(item.question) for item in items])
    median_answer_len = median([len(item.answer) for item in items])

    # Final Report
    print '---------------------------------------'
    print ' Overall Statistics'
    print '---------------------------------------'

    print 'Most common askers:' 
    print '   ',
    print ', '.join('%s (%d)' % t for t in most_common_askers)
    print
    
    print 'Total questions/answers:', len(items)
    print
    print '----------------------------------------'
    print ' Question and Answer Statistics'
    print '---------------------------------------'

    print 'Most common question words:'
    print '   ',
    print ', '.join('%s (%d)' % t for t in most_common_question_words)
    print

    print 'Most common answer words:'
    print '   ',
    print ', '.join('%s (%d)' % t for t in most_common_answer_words)
    print
    
    print 'Mean question length:   %.2f characters' % mean_question_len
    print 'Median question length: %d characters' % median_question_len
    print
    
    print 'Mean answer length:     %.2f characters' % mean_answer_len
    print 'Median answer length:   %d characters' %  median_answer_len
    print


def parse_args():
    args = sys.argv[1:]

    if len(args) != 1:
        print '%s <sqlite_db>' % sys.argv[0]
        sys.exit(1)
    else:
        return args


def get_word_counts(list_of_texts):
    """Extracts all actual words from a list of blocks of english text.
    Removes any punctuation.

    Example:
      "hello, my name is daniel! oh my, sup??"
        ->  {'hello':1, 'my':2, 'name':1, 'is':1, 'daniel':1, 'sup':1}
    """
    tokens = []
    for text in list_of_texts:        
        tokens += text.split()

    words = []    
    for token in tokens:
        token = token.lower()
        token = re.sub('(\!|\?|\.|\,)+$', '', token)
        token = re.sub('\-,\",\>,\<', '', token)
        words.append(token)

    word_counts = collections.defaultdict(int)
    for word in words:
        if word and word not in STOP_WORDS:
            word_counts[word] += 1

    return word_counts
    

def mean(ls):
    return sum(ls) / float(len(ls))


def median(ls):
    n = len(ls)
    j = int(len(ls)/2)

    if n % 2 == 0:
        return float(ls[j] + ls[j-1]) / 2
    else:
        return ls[j]


if __name__ == '__main__':
    main()
